package com.openjfx.database.mysql;

import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.statement.Statement;
import net.sf.jsqlparser.statement.create.table.CreateTable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Objects;

/**
 * SQL statement processing auxiliary class
 *
 * @author yangkui
 * @since 1.0
 */
public class SQLHelper {
    private static final String ESCAPE_SYMBOL = "`";
    private static final Logger LOG = LoggerFactory.getLogger(SQLHelper.class);

    public static String escapeSingleField(String field) {
        return ESCAPE_SYMBOL + field + ESCAPE_SYMBOL;
    }

    public static String fullTableName(String scheme, String table) {
        Objects.requireNonNull(scheme);
        Objects.requireNonNull(table);
        return ESCAPE_SYMBOL + scheme + ESCAPE_SYMBOL + "." + ESCAPE_SYMBOL + table + ESCAPE_SYMBOL;
    }

    public static String setDDLScheme(String scheme, String ddl) throws JSQLParserException {
        final Statement statement;
        try {
            statement = CCJSqlParserUtil.parse(ddl);
        } catch (JSQLParserException e) {
            LOG.error("DDL statement transfer failed!", e);
            throw e;
        }
        if (!(scheme.startsWith(ESCAPE_SYMBOL) && scheme.endsWith(ESCAPE_SYMBOL))) {
            scheme = ESCAPE_SYMBOL + scheme + ESCAPE_SYMBOL;
        }
        if (statement instanceof CreateTable) {
            var table = ((CreateTable) statement).getTable();
            table.setSchemaName(scheme);
            table.setName(table.getName());
            ((CreateTable) statement).setTable(table);
            ddl = statement.toString();
        }
        return ddl;
    }

    public static String escapeFieldValue(String val) {
        return val == null ? null : "'" + val + "'";
    }
}
